package com.gyg.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.gyg.domain.*;
import com.gyg.dao.CloudRecordMapper;
import com.gyg.enums.FileOperateEnum;
import com.gyg.returns.RespCode;
import com.gyg.returns.RespEntity;
import com.gyg.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gyg.vo.DateCountVO;
import com.gyg.vo.result.OptionResult;
import com.gyg.vo.result.RecordListResult;
import com.gyg.vo.result.RecordResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 文件上传下载记录表 服务实现类
 * </p>
 *
 * @author gyg
 * @since 2021-04-14
 */
@Service
@Slf4j
public class CloudRecordServiceImpl extends ServiceImpl<CloudRecordMapper, CloudRecord> implements CloudRecordService {

    @Lazy
    @Autowired
    private CloudPictureService cloudPictureService;

    @Lazy
    @Autowired
    private CloudDocumentService cloudDocumentService;

    @Lazy
    @Autowired
    private CloudAudioService cloudAudioService;

    @Lazy
    @Autowired
    private CloudVideoService cloudVideoService;

    @Override
    @Async
    public void fileRecordAccess(CloudRecord cloudRecord) {
        baseMapper.insert(cloudRecord);
        log.info("操作记录异步接入成功，record={}", JSONUtil.toJsonStr(cloudRecord));
    }

    @Override
    public RespEntity<List<RecordResult>> getCloudRecordTop5(Integer userId) {
        //最近的操作记录 前五条
        QueryWrapper<CloudRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CloudRecord::getUserId, userId)
                .eq(CloudRecord::getDeleted, 0)
                .orderByDesc(CloudRecord::getId)
                .last("limit 5");
        List<CloudRecord> cloudRecordList = baseMapper.selectList(queryWrapper);

        List<RecordResult> recordResultList = Lists.newArrayList();
        for (CloudRecord cloudRecord : cloudRecordList) {
            RecordResult recordResult = new RecordResult();
             switch (cloudRecord.getFileType()) {
                 case 1 : recordResult = getPictureRecord(cloudRecord.getFileId()); break;
                 case 2 : recordResult = getDocumentRecord(cloudRecord.getFileId()); break;
                 case 3 : recordResult = getAudioRecord(cloudRecord.getFileId()); break;
                 case 4 : recordResult = getVideoRecord(cloudRecord.getFileId()); break;
             }
             //操作类型：上传、下载
             recordResult.setFileOperate(FileOperateEnum.getInstance(cloudRecord.getFileOperate()).getDesc());
             recordResult.setFileTime(cloudRecord.getRecordTime());
             recordResultList.add(recordResult);
        }

        return new RespEntity<>(RespCode.SUCCESS, recordResultList);
    }

    /**
     * 组装图片信息
     * @param fileId
     * @return
     */
    private RecordResult getPictureRecord(Integer fileId) {
        CloudPicture cloudPicture = cloudPictureService.getById(fileId);
        String fileName = cloudPicture.getPictureName();
        String fileImg = cloudPicture.getPictureUrl();

        //被封禁
        if (cloudPicture.getPictureBan().equals(1)) {
            fileName = fileName + "(已被封禁)";
            fileImg = cloudPicture.getPictureImg();
        }

        RecordResult recordResult = RecordResult.builder()
                .fileName(fileName)
                .fileImg(fileImg)
                .fileSize(cloudPicture.getPictureSize())
                .build();

        return recordResult;
    }

    /**
     * 组装文档信息
     * @param fileId
     * @return
     */
    private RecordResult getDocumentRecord(Integer fileId) {
        CloudDocument cloudDocument = cloudDocumentService.getById(fileId);
        String fileName = cloudDocument.getDocumentName();

        //被封禁
        if (cloudDocument.getDocumentBan().equals(1)) {
            fileName = fileName + "(已被封禁)";
        }

        RecordResult recordResult = RecordResult.builder()
                .fileName(fileName)
                .fileImg(cloudDocument.getDocumentImg())
                .fileSize(cloudDocument.getDocumentSize())
                .build();

        return recordResult;
    }

    /**
     * 组装音频信息
     * @param fileId
     * @return
     */
    private RecordResult getAudioRecord(Integer fileId) {
        CloudAudio cloudAudio = cloudAudioService.getById(fileId);
        String fileName = cloudAudio.getAudioName();

        //被封禁
        if (cloudAudio.getAudioBan().equals(1)) {
            fileName = fileName + "(已被封禁)";
        }

        RecordResult recordResult = RecordResult.builder()
                .fileName(fileName)
                .fileImg(cloudAudio.getAudioImg())
                .fileSize(cloudAudio.getAudioSize())
                .build();

        return recordResult;
    }

    /**
     * 组装视频信息
     * @param fileId
     * @return
     */
    private RecordResult getVideoRecord(Integer fileId) {
        CloudVideo cloudVideo = cloudVideoService.getById(fileId);
        String fileName = cloudVideo.getVideoName();

        //被封禁
        if (cloudVideo.getVideoBan().equals(1)) {
            fileName = fileName + "(已被封禁)";
        }

        RecordResult recordResult = RecordResult.builder()
                .fileName(fileName)
                .fileImg(cloudVideo.getVideoImg())
                .fileSize(cloudVideo.getVideoSize())
                .build();

        return recordResult;
    }

    @Override
    public RespEntity<OptionResult> getRecordRecent7Days(Integer userId) {
        List<DateCountVO> dateCountVOList = baseMapper.getRecordRecent7Days(userId);
        //日期集合
        List<String> xaXis = dateCountVOList.stream()
                .map(DateCountVO::getDate)
                .collect(Collectors.toList());
        //数量集合
        List<Integer> yaXis = dateCountVOList.stream()
                .map(DateCountVO::getCount)
                .collect(Collectors.toList());

        return new RespEntity<>(RespCode.SUCCESS, new OptionResult(xaXis, yaXis));
    }

    @Override
    public RespEntity<RecordListResult> cloudRecordList(Integer userId, Integer pageNum, Integer pageSize) {
        QueryWrapper<CloudRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CloudRecord::getUserId, userId)
                .eq(CloudRecord::getDeleted, 0)
                .orderByDesc(CloudRecord::getId);

        IPage<CloudRecord> iPage = new Page<>(pageNum, pageSize);
        IPage<CloudRecord> page = super.page(iPage, queryWrapper);
        List<CloudRecord> cloudRecordList = page.getRecords();

        List<RecordResult> recordResultList = Lists.newArrayList();
        for (CloudRecord cloudRecord : cloudRecordList) {
            RecordResult recordResult = new RecordResult();
            switch (cloudRecord.getFileType()) {
                case 1 : recordResult = getPictureRecord(cloudRecord.getFileId()); break;
                case 2 : recordResult = getDocumentRecord(cloudRecord.getFileId()); break;
                case 3 : recordResult = getAudioRecord(cloudRecord.getFileId()); break;
                case 4 : recordResult = getVideoRecord(cloudRecord.getFileId()); break;
            }
            //操作类型：上传、下载
            recordResult.setFileOperate(FileOperateEnum.getInstance(cloudRecord.getFileOperate()).getDesc());
            recordResult.setFileTime(cloudRecord.getRecordTime());
            recordResultList.add(recordResult);
        }

        RecordListResult recordListResult = new RecordListResult();
        recordListResult.setPageNum(page.getCurrent());
        recordListResult.setPageSize(page.getSize());
        recordListResult.setPageCount(page.getPages());
        recordListResult.setTotal(page.getTotal());
        recordListResult.setRecordResultList(recordResultList);

        return new RespEntity<>(RespCode.SUCCESS, recordListResult);
    }

}
